package com.intel.factorytest.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TextView;

import com.intel.factorytest.R;

import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.content.Context;
import java.util.HashMap;
import java.util.Map;
import android.hardware.usb.UsbDevice;

import android.view.View;


public class OTGTest extends BaseActivity {//implements OnClickListener {
  private static final String TAG = "OTGTest";
  private final String KEY_STATUS="item_test_status";
  private Button passButton = null;
  private Button failButton = null;
   
  private TextView mcTestText;
  private Button mSucBtn;
  private static final String TEST_ITEM = "test_item";
  private Timer mTimer = null;
  private static final int READ_USB_DEVICE = 1;
  private boolean mAvailable = false; 
  private static final String TEST_ITEM_RESULT = "test_item_result";
  boolean is_pass = false;
  private UsbManager mUsbManager;

  @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    String orientationStr = intent.getStringExtra("sd_orientation");
    int orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
    Log.d(TAG,"orientationStr = " + orientationStr);
    if("SCREEN_ORIENTATION_PORTRAIT".equals(orientationStr)) {
        orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        super.setRequestedOrientation(orientation);

    } else if("SCREEN_ORIENTATION_LANDSCAPE".equals(orientationStr)) {
        orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        super.setRequestedOrientation(orientation);

    }
    
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);    
    Log.d(TAG,"mUsbManager = " + mUsbManager);
//      setContentView(R.layout.usb_test_insert); 
//      setTitle(R.string.usb_test);
    setContentView(R.layout.otg_test);
    mcTestText = findViewById(R.id.otg_text);
    // mcTestText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    mcTestText.setGravity(Gravity.CENTER);
    mcTestText.setTextSize(24);

    super.initView();
    mSucBtn = (Button) findViewById(R.id.success_button);
    mSucBtn.setVisibility(View.INVISIBLE);
    // setContentView(mcTestText);

    // HashMap<String, UsbDevice> deviceHashMap = ((UsbManager) getSystemService(USB_SERVICE)).getDeviceList();
    // boolean hasOTG = false;
 //    for (Map.Entry entry : deviceHashMap.entrySet()) {
 //        Log.d("hugh-tag", "detectUsbDeviceWithUsbManager: key=" + entry.getKey() + " value=" + entry.getValue());
 //        hasOTG = true;
 //    }

    // // String textString = "";
    // // String cmd = "ls sys/bus/usb/devices/";
    // // textString = callShellCmd(cmd);
    // if (hasOTG) {
    //     mcTestText.setText(getString(R.string.usb_status_host));
    // } else {
    //     mcTestText.setText(this.getString(R.string.insert_otg_cable));
    // }

    detectUsbWithBroadcast();
    }

    Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        Log.d(TAG, "OTG handleMessage what=" + msg.what);
        if(msg.what == READ_USB_DEVICE){
               
            String textString = "";
            String cmd = "ls sys/bus/usb/devices/";
            textString = callShellCmd(cmd);
            Log.d(TAG, "OTG textString=" + textString);
            if ("" != textString) {
                mcTestText.setText(getString(R.string.usb_status_host) + textString);
                is_pass = true;
                mSucBtn.setVisibility(View.VISIBLE);
            } else {
                   mcTestText.setText(getString(R.string.insert_otg_cable));
            } 
            
        }

    }
    };

    private void updateOTGStatus() {        
        Log.d(TAG, "updateOTGStatus mUsbManager = " + mUsbManager);
        HashMap<String, UsbDevice> deviceHashMap = mUsbManager.getDeviceList();
        boolean hasOTG = false;
        
        Log.d(TAG, "updateOTGStatus deviceHashMap = " + deviceHashMap);
        Log.d(TAG, "updateOTGStatus deviceHashMap.entrySet() = " + deviceHashMap.entrySet());
        for (Map.Entry entry : deviceHashMap.entrySet()) {
            Log.d(TAG, "OTGTest detectUsbDeviceWithUsbManager: key=" + entry.getKey() + " value=" + entry.getValue());
            hasOTG = true;
        }
        Log.d(TAG, "updateOTGStatus hasOTG = " + hasOTG);
        if (hasOTG) {
            mcTestText.setText(getString(R.string.usb_status_host));
            is_pass = true;
            mSucBtn.setVisibility(View.VISIBLE);
        } else {
            mcTestText.setText(this.getString(R.string.insert_otg_cable));
            is_pass = false;
            mSucBtn.setVisibility(View.INVISIBLE);
        }
    }

    private void detectUsbWithBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        filter.addAction("android.hardware.usb.action.USB_STATE");
        
        registerReceiver(mUsbStateChangeReceiver, filter);
    }
 
    private BroadcastReceiver mUsbStateChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: " + intent.getAction());
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) {
                mcTestText.setText(getString(R.string.usb_status_host));
                is_pass = true;
                mSucBtn.setVisibility(View.VISIBLE);
            } else {
                   // mcTestText.setText(getString(R.string.insert_otg_cable));
                   // is_pass = false;
                   updateOTGStatus();
            }
        }
    };

    @Override
    public void onResume() {
         super.onResume();
    // mTimer = new Timer();
    // mTimer.schedule(new TimerTask(){
            
    // @Override
    // public void run() {
    //     mHandler.sendEmptyMessage(READ_USB_DEVICE);
    // }
            
    // }, 200, 1000);
    }

    private String callShellCmd(String cmd) {
    String textString = "";    
    try {
        Process p = Runtime.getRuntime().exec(new String[]{"sh","-c",cmd});
        InputStream is = p.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String tmp = "";
    
    
        while((tmp=br.readLine())!=null){
            if (!tmp.contains("Host")) {
                textString += tmp;
            }
            
        }
        br.close();

        /*InputStream eis = p.getErrorStream();packages/apps/MAT/java/src/com/intel/factorytest/activity/OTGTest.java:167:
        InputStreamReader eisr = new InputStreamReader(eis);
        BufferedReader ebr = new BufferedReader(eisr);

        while((tmp=ebr.readLine())!=null){
            textString += tmp;
        }
        ebr.close();*/
        p.destroy();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    return textString;

    }



    @Override
    public void onDestroy() {    
     Log.d(TAG, "onDestroy");
     super.onDestroy();
     unregisterReceiver(mUsbStateChangeReceiver);
     if(mTimer!=null){
         mTimer.cancel();
     }
    }
 

    // private void setTestResult () {
    //     Intent intent = new Intent();
    //     Intent mIntent = getIntent();
    //     int pos = mIntent.getIntExtra(TEST_ITEM,-1);
    //     intent.putExtra(TEST_ITEM,pos);
    //     intent.putExtra(TEST_ITEM_RESULT,is_pass);
    //     setResult(0, intent);
    // }
    @Override
    public void finish() {
        setTestResult (); 
        super.finish();
    }
}
